#include <pthread.h>

#include <iostream>
#include <unistd.h>

int ticknumber = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *ticket(void *args)
{
    char* id = (char*)args;
    while (true)
    {
        pthread_mutex_lock(&mutex);
        //条件判断 （TODO..）
        printf("%s 陷入等待\n",id);
        pthread_cond_wait(&cond,&mutex);
        printf("%s 被唤醒\n",id); //被唤醒的要先去申请锁, 如果申请了在继续走下去, 没有申请到的, 阻塞等待申请到锁
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, nullptr, ticket, (void*)"thread-1");
    pthread_create(&t2, nullptr, ticket, (void*)"thread-2");
    pthread_create(&t3, nullptr, ticket, (void*)"thread-3");
    pthread_create(&t4, nullptr, ticket, (void*)"thread-4");

    sleep(2); //一开始所有的线程都进行等待
    while(true){
        // pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        //效果：唤醒一个 -> 陷入等待 -> 唤醒一个 。。。。
        sleep(1);
    }

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    return 0;
}